package com.bree.erp.service.stateless;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;

import com.bree.erp.entity.Address;
import com.bree.erp.entity.PhoneType;
import com.bree.erp.entity.Supplier;
import com.bree.erp.service.SupplierService;

@Stateless
public class SupplierServiceBean implements SupplierService {

	@PersistenceContext()
	private EntityManager em;
	
	public SupplierServiceBean() {
		
	}
	
	public SupplierServiceBean(EntityManager em) {
		this.em = em;
	}
	
	@Override
	public Supplier create(String name, String remarks) {
		
		Supplier supplier = new Supplier();
		
		supplier.setName(name);
		supplier.setRemarks(remarks);
		
		em.persist(supplier);
		
		return supplier;
	}

	@Override
	public Supplier read(Long id) {
		
		return em.find(Supplier.class, id);
	}

	@Override
	public Supplier update(Long id, String name, String remarks) {
		Supplier supplier = read(id);
		
		supplier.setName(name);
		supplier.setRemarks(remarks);
		
		return supplier;
	}

	@Override
	public Supplier update(Long id, Address address) {

		Supplier supplier = read(id);
		
		supplier.setAddress(address);
		
		return supplier;
	}

	@Override
	public Supplier update(Long id, PhoneType type, String phoneDetail) {
		
		Supplier supplier = read(id);

		Map<PhoneType, String> phones = supplier.getPhoneNumbers();
		if(phones == null) {
			phones = new HashMap<PhoneType, String>();
			supplier.setPhoneNumbers(phones);
		}
		
		phones.put(type, phoneDetail);
		
		return supplier;
	}

	@Override
	public void delete(Long id) {
		Supplier supplier = read(id);
		
		em.remove(supplier);
		
	}

	@Override
	public Collection<Supplier> list() {
		
		TypedQuery<Supplier> query = em.createNamedQuery(Supplier.QUERY_SELECT_ALL_SUPPLIER, Supplier.class);
		
		return query.getResultList();
	}

}
